#include "PathInfo.h"
#include <Log.h>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>
using namespace CSDatabaseLib;
PathInfo::PathInfo(PathInfo *parent, const std::string &name): m_name(name), m_parent(parent) {
	m_id = 0;
	m_rights = 0;
	m_owner = 0;
	m_group = 0;
	m_storage_id = 0;
	m_type = PATH_UNKNOWN;
	if (m_parent != NULL)
	{
		m_parent->m_child = this;
	}
	m_child = NULL;
	m_syncTime = 0;
    m_modTime = 0;
    m_Time = 0;
	m_exists = false;
}

PathInfo::~PathInfo()
{
	if (m_child!=NULL)
	{
		m_child->m_parent = NULL;
		delete m_child;
	}
	m_child = NULL;

	if (m_parent!=NULL)
	{
		m_parent->m_child = NULL;
		delete m_parent;
	}
	m_parent = NULL;
}

inline bool IsDirectParent(const std::string &link, const std::string &parentLink)
{
	if ((link == parentLink) || parentLink.empty() || link.empty())
		return false;
	if (link.length()<=parentLink.length())
		return false;

	if (!boost::starts_with(link, parentLink))
		return false;

	std::string left;
	if ((parentLink[parentLink.length()-1] != '/') && (parentLink[parentLink.length()-1] != '\\'))
	{
		left = link.substr(parentLink.length());
	}
	else
	{
		left = link.substr(parentLink.length()-1);
	}
	if (left.empty())
		return false;
	if (left[0] != '/' && left[0]!='\\')
		return false;
	if (std::count(left.begin(), left.end(), '/')+std::count(left.begin(), left.end(), '\\')!=1)
		return false;
	return true;
}

bool PathInfo::IsDirectStorageChild() const
{
	if (NULL == m_parent) return false;
	if (m_parent->m_storage_id == 0) return false;
	if (m_parent->m_link.empty()) return false;
	if (!m_parent->m_exists) return false;

	if (m_storage_id == 0) return false;
	if (m_link.empty()) return false;
	if (!m_exists) return false;

	if (m_storage_id!=m_parent->m_storage_id) return false;
	return IsDirectParent(m_link, m_parent->m_link);
}

